import { FormTypes, getListData } from '@/utils/JEditableTableUtil'
import {
  findBySelectSup,
  getAllList,
  findBySelectCus,
  findBySelectNotTenantCus,
  findBySelectRetail,
  getMaterialByBarCode,
  getMaterialByUnit,
  findStockByDepotAndBarCode,
  getAccount,
  getPersonByNumType,
  getBatchNumberList,
  getDiscount,
  getNumber,
  getSpecial,
  findFinancialDetailByNumber,
  findBillDetailByNumber,
  getCurrentSystemConfig
} from '@/api/api'
import { getAction, putAction } from '@/api/manage'
import { getMpListShort, getNowFormatDateTime, randomUUID} from '@/utils/util'
import {getSubType} from '@/utils/detailType'
import { USER_INFO } from '@/store/mutation-types'
import Vue from 'vue'
import { param } from 'jquery'
import { options } from 'less'
import {toDecimal} from '@/utils/calculate';
export const BillModalMixin = {
  data () {
    return {
      action: '',
      manyAccountBtnStatus: false,
      localStorageKeyJson: {},
      supList: [],
      addressList: [],
      warehouseList: [],
      cusList: [],
      retailList: [],
      personList: {
        options: [],
        value: ''
      },
      arrList: [],
      shopBarCode: '',
      shopMaterialId: '',
      shopIdList: [],
      arrUnit: [],
      materialIds: '',
      organId: '',
      depotList: [],
      accountList: [],
      accountIdList: [],
      accountMoneyList: [],
      disabledRowIds:[],//禁用的行
      transportList:[],//运输公司
      billUnitPirce: '',
      scanBarCode: '',
      scanStatus: true,
      fileLoading:false,
      billStatus: '0',
      minWidth: 1100,
      isCanCheck: true,
      isTenant: false,
      submitBtnDisabled: false,//提交按钮禁用
      showPrice:true,//根据是否显示采购价显示discountLastMoney
      materialColor:'',
      validatorRules: {
        price: {
          rules: [
            {
              pattern: /^(([0-9][0-9]*)|([0]\.\d{0,4}|[0-9][0-9]*\.\d{0,4}))$/,
              required: true,
              message: '金额格式不正确!'
            }
          ]
        },
        backAmount: {
          rules: [
            {
              required: true,
              message: '找零不能为空!'
            }
          ]
        },
        discountLastMoney: {
          rules: [{ required: true, message: '优惠后金额不能为空!' }]
        },
        discount: {
          rules: [{ required: true, message: '优惠率不能为空!' }]
        },
        otherMoney: {
          rules: [{ required: true, message: '其它费用不能为空!' }]
        },
        discountMoney: {
          rules: [{ required: true, message: '退款优惠不能为空!' }]
        },
        changeAmount: {
          rules: [{ required: true, message: '本次退款不能为空!' }]
        },
        debt: {
          rules: [{ required: true, message: '本次欠款不能为空!' }]
        }
      },
      spans: {
        labelCol1: { span: 2 },
        wrapperCol1: { span: 22 },
        //1_5: 分为1.5列（相当于占了2/3）
        labelCol1_5: { span: 3 },
        wrapperCol1_5: { span: 21 },
        labelCol2: { span: 4 },
        wrapperCol2: { span: 20 },
        labelCol3: { span: 6 },
        wrapperCol3: { span: 18 },
        labelCol6: { span: 12 },
        wrapperCol6: { span: 12 }
      }
    }
  },
  created () {
    let userInfo = Vue.ls.get(USER_INFO)
    this.isTenant = userInfo.id === userInfo.tenantId ? true : false
    let realScreenWidth = window.screen.width
    this.width = realScreenWidth < 1500 ? '1300px' : '1550px'
    this.minWidth = realScreenWidth < 1500 ? 1250 : 1500
  },
  computed: {
    readOnly: function () {
      return this.action !== 'add' && this.action !== 'edit'
    }
  },
  methods: {
    getSubType,
    // 订单编辑前
    editBefore(){
      // 获取页面权限
      this.initActiveBtnStr()
      if(!(this.btnEnableList.indexOf(8) > -1)){
        this.editPrice(0)
      }else{
        this.editPrice(1)
      }
    },
    // 校验jedittable 数字大于0
    validateCheckNumber(type, value, row, column, callback, target) {
      let allValues = target.inputValues
      let currentRow = allValues.find(v=>v.id.includes(row.id))
      if(+value <= 0 && currentRow && !currentRow.sourceId){
        callback(false,this.$t('otherJS.greaterThan0'))
        return
      }else if(currentRow && currentRow.sourceId && (value === '' || +value !== 0)){
        callback(false,this.$t('otherJS.giftPrice0'))
      } else{
        callback(true)
      } 
    },
    openFinancialDetail (billNo, type) {
      findFinancialDetailByNumber({billNo}).then(res => {
        this.$refs.FinancialDetail.show(res.data, type)
        this.$refs.FinancialDetail.title = type
      })
    },
    openBillDetail (number, type) {
      findBillDetailByNumber({number}).then(res => {
        this.$refs.BillDetail.show(res.data, type)
        this.$refs.BillDetail.title = type 
      })
    },
    // 获取localStorage数据
    getLocalStorage (key) {
      var value = localStorage.getItem(key) // 取回 value 变量
      this.localStorageKeyJson = JSON.parse(value)
      return this.localStorageKeyJson.value
    },
    // 没有修改价格权限就禁止编辑
    /**
     * 
     * @param {type} 1,0
     */
    editPrice(type) {
      let array = ['unitPrice','allPrice','taxRate','taxMoney','taxUnitPrice','taxLastMoney']
      array.forEach(v=>{
        this.changeFormTypesToInput(this.materialTable.columns, v, type)
      })
    },
    /**
     * 区分本租户的仓库和别人的仓库
     */
    getAnotherDepotData() {
      getAction('/depot/findDepotList').then(res => {
        if (res.code === 200) {
          this.anotherDepotList = res.data
          let creator = this.getLocalStorage('pro__Login_Userinfo').tenantId
          this.selfDepot = this.anotherDepotList.filter(v=>v.tenantId === creator)
          this.othoerDepot = this.anotherDepotList.filter(v=>v.tenantId !== creator)
        } else {
          this.$message.info(res.data)
        }
      })
    },
    // Modald点击新增触发
    addInit (amountNum) {
      if(amountNum){ //传入前缀才生成
        /*生成短的单据编号 */
        // const buildHeadNumber = ()=> getAction('/sequence/buildHeadNumber')
        /*生成长的单据编号 */
        const buildNumber = ()=> getAction('/sequence/buildNumber')
        Promise.all([buildNumber(),getCurrentSystemConfig()]).then(res=>{
          if (res[0] && res[0].code === 200 && res[1] && res[1].code === 200) {
            const sysPrefixNo = res[1].data && res[1].data.companyPostCode || ''
            Vue.ls.set('taxRate',res[1].data.companyContacts)
            if(!sysPrefixNo){
              this.$message.error(this.$t('otherJS.yetSetPrefix'))
              return;
            }
            if (
              amountNum === 'YFDD' || 
              amountNum === 'FKDD' || 
              amountNum === 'ZFYF' || 
              amountNum === 'ZFFK' ||
              amountNum === 'ZFSK' ||
              amountNum === 'SK' ||
              amountNum === 'FLLS'
            ) {
            this.$nextTick(()=>{
              this.form.setFieldsValue({
                billNo:amountNum ? sysPrefixNo + amountNum + res[0].data.defaultNumber : '',
              }) // 运费单新增会用
            })
            }else{
              this.$nextTick(()=>{
              this.form.setFieldsValue({ number: sysPrefixNo + amountNum + res[0].data.defaultNumber })
                
              })
            }
            this.$nextTick(()=>{
              this.form.setFieldsValue({ promotionNo: sysPrefixNo + amountNum + res[0].data.defaultNumber })
            this.form.setFieldsValue({ rebateCode: sysPrefixNo + amountNum + res[0].data.defaultNumber })
            })
          }else{
            this.$message.error(res[1].msg || res[0].msg)
          }
        }).catch(e=>{
          console.log('e :>> ', e);
        })
        
      }
      this.$nextTick(() => {
        this.form.setFieldsValue({
          operTime: getNowFormatDateTime(),
          tabulationTime: getNowFormatDateTime(),
          discount: 0,
          discountMoney: 0,
          discountLastMoney: 0,
          otherMoney: 0,
          changeAmount: 0,
          debt: 0,
          backAmount: 0,
          userName: this.getLocalStorage('pro__Login_Userinfo').loginName,
          creator: this.getLocalStorage('pro__Login_Userinfo').id
        })
      })
      this.$nextTick(() => {
        getAccount({}).then(res => {
          if (res && res.code === 200) {
            for (const item of res.data.accountList) {
              if (item.isDefault) {
                this.form.setFieldsValue({ accountId: item.id })
              }
            }
          }
        })
      })
      this.accountIdList = []
      this.accountMoneyList = []
      this.manyAccountBtnStatus = false
    },
    copyAddInit (amountNum) {
      getAction('/sequence/buildNumber').then(res => {
        if (res && res.code === 200) {
          this.form.setFieldsValue({ number: amountNum + res.data.defaultNumber })
        }
      })
      this.getLocalStorage('pro__Login_Userinfo')
      this.$nextTick(() => {
        this.form.setFieldsValue({ operTime: getNowFormatDateTime(), tabulationTime: getNowFormatDateTime() })
      })
    },
    /** 查询某个tab的数据 */
    requestSubTableData (url, params, tab, success) {
      tab.loading = true
      getAction(url, params)
        .then(res => {
          if (res && res.code === 200) {
            tab.dataSource = res.data.rows
            for (let i = 0; i < tab.dataSource.length; i++) {
              tab.dataSource[i].meId = tab.dataSource[i].materialExtendId
              if (this.url.release == '/depotHead/getIssuePurchase') {
                tab.dataSource[i].unitPrice = tab.dataSource[i].billPrice
                tab.dataSource[i].taxUnitPrice = (
                  tab.dataSource[i].unitPrice /
                  ((100 + tab.dataSource[i].taxRate) / 100)
                ).toFixed(2)
                tab.dataSource[i].taxMoney = (
                  tab.dataSource[i].allPrice -
                  tab.dataSource[i].taxUnitPrice * tab.dataSource[i].operNumber
                ).toFixed(2)
                tab.dataSource[i].taxLastMoney = tab.dataSource[i].allPrice
              }
              let info = tab.dataSource[i]
              this.changeColumnShow(info)
            }
            // if(this.prefixNo === 'CGDD' && ){
            //   tab.dataSource = tab.dataSource.filter(v=> v.preNumber > v.finishNumber)
            // }
            typeof success === 'function' ? success(res) : ''
          }
        })
        .finally(() => {
          tab.loading = false
        })
    },
    
    //改变字段的状态，1-显示 0-隐藏
    changeFormTypesToInput (columns, key, type) {
      for (let i = 0; i < columns.length; i++) {
        if (columns[i].key === key) {
          if(type){
            columns[i].type = FormTypes.inputNumber
          }else{
            columns[i].type = FormTypes.normal
          }
        }
      }
    },
    //改变字段的状态，1-显示 0-隐藏
    changeFormTypes (columns, key, type) {
      for (let i = 0; i < columns.length; i++) {
        if (columns[i].key === key) {
          if (type) {
            if (key === 'snList' || key === 'batchNumber') {
              if (
                this.prefixNo === 'LSCK' ||
                this.prefixNo === 'CGTH' ||
                this.prefixNo === 'XSCK' ||
                this.prefixNo === 'QTCK' ||
                this.prefixNo === 'DBCK'
              ) {
                columns[i].type = FormTypes.popupJsh //显示
              } else {
                columns[i].type = FormTypes.input //显示
              }
            } else if (key === 'expirationDate') {
              if (
                this.prefixNo === 'LSTH' ||
                this.prefixNo === 'CGRK' ||
                this.prefixNo === 'XSTH' ||
                this.prefixNo === 'QTRK'
              ) {
                columns[i].type = FormTypes.date //显示
              } else {
                columns[i].type = FormTypes.normal //显示
              }
            } else if (key === 'differNumber') {
              console.log('进入differNumber', type)
              if (type == 1) {
                columns[i].type = FormTypes.normal //显示 不能输入
              } else {
                columns[i].type = FormTypes.inputNumber //显示
              }
            }else if (key === 'name') {
              if (type == 1) {
                columns[i].type = FormTypes.normal //显示 不能输入
              } else {
                columns[i].type = FormTypes.popupJsh //显示
              }
            } else {
              columns[i].type = FormTypes.normal //显示
            }
          } else {
            columns[i].type = FormTypes.hidden //隐藏
          }
        }
      }
    },
    initSupplier () {
      let that = this
      findBySelectSup({}).then(res => {
        if (res) {
          that.supList = res
        }
      })
    },
    // 地址
    initAddressList () {
      let that = this
      getAllList({}).then(res => {
        // console.log('Modal')
        if (res.data) {
          that.addressList = res.data
        }
      })
    },
    // 获取仓库
    initWarehouseList () {
      getAction('/depot/findDepotByCurrentUser').then(res => {
        if (res.data) {
          this.warehouseList = res.data
        }
      })
    },
    
    initDepot () {
      let that = this
      getAction('/depot/findDepotByCurrentUser').then(res => {
        if (res.code === 200) {
          let arr = res.data
          for (let item of that.materialTable.columns) {
            if (item.key == 'depotId' || item.key == 'anotherDepotId') {
              item.options = []
              for (let i = 0; i < arr.length; i++) {
                let depotInfo = {}
                depotInfo.value = arr[i].id + '' //注意-此处value必须为字符串格式
                depotInfo.text = arr[i].depotName
                depotInfo.title = arr[i].depotName
                depotInfo.depotName = '仓库'
                item.options.push(depotInfo)
              }
            }
          }
        }
      })
    },
    initCustomerNotTenant () {
      let that = this
      findBySelectNotTenantCus({}).then(res => {
        if (res) {
          that.cusList = res
        }
      })
    },
    initCustomer () {
      let that = this
      findBySelectCus({}).then(res => {
        if (res) {
          that.cusList = res
        }
      })
    },
    
    initRetail () {
      let that = this
      findBySelectRetail({}).then(res => {
        if (res) {
          that.retailList = res
        }
      })
    },
    initSalesman () {
      let that = this
      getPersonByNumType({ type: 1 }).then(res => {
        if (res) {
          that.personList.options = res
        }
      })
    },
    changeMaterialIds () {
      let that = this
      getAction('/materialsExtend/getDetailByMaterialId?materialId=' + this.materialIds).then(res => {
        if (res.code === 200) {
          let arr = res.data.rows
          this.arrUnit = res.data.rows
          // console.log('that.materialTable')
          // console.log(that.materialTable)
          for (let item of that.materialTable.columns) {
            if (item.key == 'unit') {
              item.options = []
              for (let i = 0; i < arr.length; i++) {
                let depotInfo = {}
                depotInfo.value = arr[i].meId + '' //注意-此处value必须为字符串格式

                depotInfo.text = arr[i].commodityUnit
                depotInfo.title = arr[i].commodityUnit
                depotInfo.materialId = arr[i].materialId
                this.arrList.push(depotInfo)
                // item.options.push(depotInfo)
              }
              for (let q = 0; q < this.arrList.length; q++) {
                item.options.push(this.arrList[q])
              }
              // console.log(item.options)
            }
          }
          // console.log('yyyy')
          // console.log(this.arrList)
        }
      })
    },
    fileItemList (record) {
      if(!record || !record.id) {
        this.fileList = []
        return
      }
      let params = {
        id: record.id
      }
      if(record.id === localStorage.getItem('fileListId')) {
        this.fileList = localStorage.getItem('fileList')
        return;
      }
      
      getAction('/attachment/getAttachmentListById', params).then(res => {
        if (res.code === 200) {
          let arr = res.data
          arr.forEach(file => {
            file.headerId = file.headerId || randomUUID()
            file.deleteFlag = file.deleteFlag || 0
            file.uploadFlag = file.uploadFlag || 0
            file.uid = file.uid || randomUUID()
            file.tenantId = file.tenantId || randomUUID()
            file.status = file.status || 'done'
            file.name = file.name || file.fileName
            
            if (file.response) {
              file.url = file.response.url;
              fileItemList.push(file.response.data)
              file.flag = '0'
            }else{
            file.flag =  '1'
            }
          })

          this.fileList = (res.data || []).map(v=>{
            return  {
              uid :v.id,
              url :v.data,
              flag :'1',
              status :'done',
              name :v.fileName,
              data:v.data,
              type:v.type
            }
          })
          
          localStorage.setItem('fileList', JSON.stringify(arr))
          localStorage.setItem('fileListId', JSON.stringify(record.id))
        }
      }).then(()=>{
        this.$set(this.model,'uploadKey',randomUUID())
      })
    },
    getSupplier () {
      let that = this
      let param = {
        search: { type: '供应商' },
        currentPage: '1',
        pageSize: '10'
      }
      getAction('/supplier/list', param).then(res => {
        if (res.code === 200) {
          let arr = res.data.rows
          for (let item of that.materialTable.columns) {
            if (item.key == 'organName') {
              item.options = []
              for (let i = 0; i < arr.length; i++) {
                let depotInfo = {}
                depotInfo.value = arr[i].id + '' //注意-此处value必须为字符串格式
                depotInfo.text = arr[i].supplier
                depotInfo.title = arr[i].supplier
                item.options.push(depotInfo)
              }
            }
          }
          this.materialTable.dataSource.forEach((data, index) => {
            arr.forEach((item, index1) => {
              if (item.supplier == data.organName) {
                data.organName = item.id
              }
            })
          })
        }
      })
    },
    // initDepot () {
    //   let that = this
    //   getAction('/depot/findDepotByCurrentUser').then(res => {
    //     if (res.code === 200) {
    //       let arr = res.data
    //       for (let item of that.materialTable.columns) {
    //         if (item.key == 'depotId' || item.key == 'anotherDepotId') {
    //           item.options = []
    //           for (let i = 0; i < arr.length; i++) {
    //             let depotInfo = {}
    //             depotInfo.value = arr[i].id + '' //注意-此处value必须为字符串格式
    //             depotInfo.text = arr[i].depotName
    //             depotInfo.title = arr[i].depotName
    //             depotInfo.depotName = '仓库'
    //             item.options.push(depotInfo)
    //           }
    //         }
    //       }
    //     }
    //   })
    // },
    //默认报损
    
    initBreak () {
      let that = this
      for (let item of that.materialTable.columns) {
        if (item.key == 'custom11') {
          item.options = [
            { text: this.$t('manuManagement.breakageTypeNormal'), title: this.$t('manuManagement.breakageTypeNormal'), value: '0' },
            { text: this.$t('manuManagement.breakageTypeBreaked'), title: this.$t('manuManagement.breakageTypeBreaked'), value: '1' },
            { text: this.$t('manuManagement.breakageTypeExchanged'), title: this.$t('manuManagement.breakageTypeExchanged'), value: '2' }
          ]
        }
      }
    },
    // 默认运输公司
    initTransport () {
      let that = this
      let arr =[]
      getAction('/transport/getAllList', param).then(res => {
        if (res.code === 200) {
          console.log(res,666);
          arr = (res.data || []).filter(v=> v.transpotName && v.transpotName)
          this.transportList = arr
          for (let item of that.materialTable.columns) {
            if (item.key == 'transpotName') {
              item.options = arr.map(v=>{
                let obj ={
                  text: v.transportName || v.transpotName,
                  title: v.transportName || v.transpotName,
                  value:v.transportNo || v.transpotNo
                }
                return obj
              })
            }
            
          }
        }
      })
      
    },
    // 是否厂家付款
    initIsPayByFactory() {
      let that = this
      for (let item of that.materialTable.columns) {
       if (item.key == 'paymentType') {
         item.options = [
           { text: this.$t('reportQuery.yes'),title:this.$t('reportQuery.yes'),  value: 1 },
           { text: this.$t('reportQuery.no'),title:this.$t('reportQuery.no'),  value: 0 },
         ]
       }
      }
    },
    initDepot () {
      let that = this
      getAction('/depot/findDepotByCurrentUser').then(res => {
        if (res.code === 200) {
          let arr = res.data
          for (let item of that.materialTable.columns) {
            if (item.key == 'depotId' || item.key == 'anotherDepotId') {
              item.options = []
              for (let i = 0; i < arr.length; i++) {
                let depotInfo = {}
                depotInfo.value = arr[i].id + ''
                depotInfo.text = arr[i].depotName
                depotInfo.title = arr[i].depotName
                depotInfo.depotName = '仓库'
                item.options.push(depotInfo)
              }
            }
          }
        }
      })
    },
    initAccount () {
      let that = this
      getAccount({}).then(res => {
        if (res && res.code === 200) {
          let list = res.data.accountList
          list.splice(0, 0, { id: 0, name: this.$t('popup.multiAccountStr') })
          that.accountList = list
        }
      })
    },
    handleManyAccount () {
      this.selectAccount(0)
    },
    selectAccount (value) {
      if (value === 0) {
        //多账户
        this.$refs.manyAccountModalForm.edit(this.accountIdList, this.accountMoneyList)
        this.$refs.manyAccountModalForm.title = this.$t('popup.multiAccountSettlement')
        this.manyAccountBtnStatus = true
      } else {
        this.accountIdList = []
        this.accountMoneyList = []
        this.manyAccountBtnStatus = false
      }
    },
    priceFormulaModalFormOk () {},
    goodsSourceModalFormOk () {},
    singleSourceModalFormOk () {},
    manyAccountModalFormOk (idList, moneyList, allPrice) {
      console.log(idList,moneyList,allPrice)
      this.accountIdList = idList
      this.accountMoneyList = moneyList
      let discountLastMoney = this.form.getFieldValue('discountLastMoney') - 0
      let otherMoney = this.form.getFieldValue('otherMoney') ? this.form.getFieldValue('otherMoney') - 0 : 0
      let debt = (discountLastMoney + otherMoney - allPrice).toFixed(2)
      this.$nextTick(() => {
        this.form.setFieldsValue({ changeAmount: allPrice, debt: debt })
      })
    },
    addSupplier () {
      this.$refs.vendorModalForm.add()
      this.$refs.vendorModalForm.title = this.$t('popup.newSupplier')
      this.$refs.vendorModalForm.disableSubmit = false
    },
    addCustomer () {
      this.$refs.customerModalForm.add()
      this.$refs.customerModalForm.title = this.$t('popup.newFind')
      this.$refs.customerModalForm.disableSubmit = false
    },
    addMember () {
      this.$refs.memberModalForm.add()
      this.$refs.memberModalForm.title = this.$t('popup.newMember')
      this.$refs.memberModalForm.disableSubmit = false
    },
    handleBatchSetDepot () {
      this.$refs.batchSetDepotModalForm.add()
      this.$refs.batchSetDepotModalForm.title = this.$t('popup.batchSetWarehouse')
      this.$refs.batchSetDepotModalForm.disableSubmit = false
    },
    addDepot () {
      this.$refs.depotModalForm.add()
      this.$refs.depotModalForm.title = this.$t('popup.newWarehouse')
      this.$refs.depotModalForm.disableSubmit = false
    },
    addAccount () {
      this.$refs.accountModalForm.add()
      this.$refs.accountModalForm.title = this.$t('popup.newAccount')
      this.$refs.accountModalForm.disableSubmit = false
    },
    vendorModalFormOk () {
      this.initAddressList()
      this.initSupplier()
    },
    customerModalFormOk () {
      this.initCustomer()
    },
    memberModalFormOk () {
      this.initRetail()
    },
    batchSetDepotModalFormOk (depotId) {
      this.getAllTable()
        .then(tables => {
          return getListData(this.form, tables)
        })
        .then(allValues => {
          this.form.validateFields((err, values) => {
            this.materialIds = localStorage.getItem('materialIds')
            console.log('this.materialIds')
            console.log(this.materialIds)
            //获取单据明细列表信息
            let detailArr = allValues.tablesValue[0].values
            let barCodes = ''
            for (let detail of detailArr) {
              barCodes += detail.barCode + ','
            }
            if (barCodes) {
              barCodes = barCodes.substring(0, barCodes.length - 1)
            }

            let param = {
              // barCode: barCodes,
              depotId: depotId,
              mpList: getMpListShort(Vue.ls.get('materialPropertyList')), //扩展属性
              prefixNo: this.prefixNo,
              materialId: this.materialIds,
              organId: values.organId
            }
            getMaterialByBarCode(param).then(res => {
              if (res && res.code === 200) {
                let mList = res.data
                //构造新的列表数组，用于存放单据明细信息
                let newDetailArr = []
                if (mList && mList.length) {
                  for (let i = 0; i < detailArr.length; i++) {
                    let item = detailArr[i]
                    item.depotId = depotId
                    for (let j = 0; j < mList.length; j++) {
                      if (mList[j].mBarCode === item.barCode) {
                        item.stock = mList[j].stock
                      }
                    }
                    newDetailArr.push(item)
                  }
                } else {
                  for (let i = 0; i < detailArr.length; i++) {
                    let item = detailArr[i]
                    item.depotId = depotId
                    newDetailArr.push(item)
                  }
                }
                this.materialTable.dataSource = newDetailArr
              } else {
                this.$message.error(res.data)
              }
            })
          })
        })
    },
    depotModalFormOk () {
      this.initDepot()
    },
    accountModalFormOk () {
      this.initAccount()
    },
    onAdded (event) {
      const { row, target } = event
      target.setValues([{ rowKey: row.id, values: { operNumber: 0 } }])
      getAction('/depot/findDepotByCurrentUser').then(res => {
        if (res.code === 200) {
          let arr = res.data
          for (let i = 0; i < arr.length; i++) {
            if (arr[i].isDefault) {
              target.setValues([{ rowKey: row.id, values: { depotId: arr[i].id + '' } }])
            }
          }
        }
      })
      // 聚焦新增的行
      this.$nextTick(()=>{
        const input = document.querySelectorAll(`#name${target.caseId+row.id + target.tempId} input`)
        setTimeout(()=>{
          input && input.length && (input[0].value = '')
        },200);
        input && input.length && input[0].focus()
        target.setValues([{ rowKey: row.id, values: { name: ''} }])
      })
      
    },
    unique (arr) {
      const res = new Map()
      return arr.filter(
        arr => !res.has(arr.materialId && arr.barCode) && res.set(arr.materialId && arr.barCode, arr.materialId)
      )
    },
    shopRowList (val) {
      this.giftCurrentIndex = val
      console.log(this.materialTable.dataSource,'this.materialTable.dataSource7');
      this.materialTable1.dataSource = (this.materialTable.dataSource[val] && this.materialTable.dataSource[val].shopIdList) || []
      // 以下是以前逻辑
      // let arr = []
      // console.log('val', val)
      // if (this.materialTable.dataSource.length > 0 && this.materialTable.dataSource[val]) {
      //   this.shopMaterialId = this.materialTable.dataSource[val].materialId
      //   this.shopBarCode = this.materialTable.dataSource[val].barCode
      //   this.shopIdList.forEach(item1 => {
      //     if (item1.deleteFlag) {
      //       if (this.materialTable.dataSource[val].id == item1.itemId) {
      //         // console.log('item1')
      //         // console.log(item1)
      //         arr.push(item1)
      //       }
      //     } else {
      //       if (this.materialTable.dataSource[val].materialId == item1.itemId) {
      //         // console.log('item2')
      //         // console.log(item1)
      //         arr.push(item1)
      //       }
      //     }
      //   })
      //   console.log(arr,'arr--------');

      //   this.materialTable1.dataSource = arr 
      // }
      // 以前已注释
      // this.materialTable.dataSource.forEach(item => {
      //   item.shopId =
      // });
      // if (this.materialTable.dataSource.length > 0) {
      //   let param = {
      //     itemId: this.materialTable.dataSource[val].materialId
      //   }
      //   getAction('/promotionHead/getGiftDetailList', param).then(res => {
      //     if (res.code === 200) {
      //     }
      //   })
      // }
    },
    fn2 (arr) {
      const res = new Map()
      return arr.filter(arr => !res.has(arr.id) && res.set(arr.id, arr.id))
    },
    fn3 (arr) {
      const res = new Map()
      return arr.filter(arr => !res.has(arr.barCode) && res.set(arr.barCode, arr.barCode))
    },
    setQuotationNumberInputType (event) {
      const { target, row } = event
      const input = target.el.inputTable.querySelector(`input[id*='differNumber${target.caseId+row.id}']`)
      let differNumberValue = 0
      if (row.custom11 == 0) {
        input && (input.disabled = true)
        differNumberValue = 0
      } else {
        input && (input.disabled = false)
        differNumberValue = ''
      }
      target.setValues([
        {
          rowKey: row.id,
          values: {
            differNumber: differNumberValue
          }
        }
      ]);
    },
    setGiftNumberInputType (target, row, disabled=true) {
      // if(!row.sourceId) return 
      for(let i=0;i<this.materialTable.columns.length - 1;i++){
        let mInfo = this.materialTable.columns[i]
        const input = document.querySelectorAll(`#${mInfo.key}${target.caseId+row.id}`)[0]
        const span = document.querySelector(`#${mInfo.key}${target.caseId+row.id} .ant-input-suffix`)
        if(span){
          span.style.display = 'none'
          const childInput = document.querySelector(`#${mInfo.key}${target.caseId+row.id} input`)
          childInput && (childInput.disabled = disabled)
        }
        input && (input.disabled = disabled)
      }
    },
    setLoading(){
      this.submitBtnDisabled = true;
    },
    //单元值改变一个字符就触发一次
    onValueChange (event) {
      console.log('handler: onValueChange', event)
      // console.log('触发修改事件onValueChange')
      let that = this
      // let materialIds = ''
      const { type, row, column, value, target } = event
      let param, snList, batchNumber, operNumber, unitPrice, allPrice, taxRate, taxMoney, taxUnitPrice, taxLastMoney
      // console.log(type, row, column, value, target)
      this.materialIds = localStorage.getItem('materialIds')
      // row.materialId = row.id
      switch (column.key) {
        case 'differNumber':
          if (Number(value) > Number(row.operNumber)) {
            target.setValues([
              {
                rowKey: row.id,
                values: {
                  differNumber: row.operNumber
                }
              }
            ])
          }
          break
        case 'custom11':
          this.setQuotationNumberInputType(event)
          break
        case 'depotId':
          if (row.meId) {
            that.getStockByDepotBarCode(row, target)
          }
          break
        // case 'unit':
        //   this.form.validateFields((err, values) => {
        //     this.arrUnit.forEach(item => {
        //       if (item.meId == row.unit) {
        //         param = {
        //           meId: item.meId,
        //           prefixNo: this.prefixNo,
        //           supplierId: values.organId,
        //           depotId: row.depotId
        //         }
        //         getMaterialByUnit(param).then(res => {
        //           if (res && res.code === 200) {
        //             let mList = res.data
        //             let meId = mList[0].meId
        //             //单个条码
        //             findStockByDepotAndBarCode({ depotId: row.depotId, meId: meId }).then(res => {
        //               if (res && res.code === 200) {
        //                 let mArr = []
        //                 let mInfo = mList[0]
        //                 this.changeColumnShow(mInfo)
        //                 let mInfoEx = this.parseInfoToObj(mInfo)
        //                 mInfoEx.stock = res.data.stock
        //                 let mObj = {
        //                   rowKey: row.id,
        //                   values: mInfoEx
        //                 }
        //                 console.log(mObj)
        //                 mArr.push(mObj)
        //                 target.setValues(mArr)
        //                 target.recalcAllStatisticsColumns()
        //                 that.autoChangePrice(target)
        //                 this.$refs.materialDataTable.getValues((error, values) => {
        //                 })
        //                 target.autoSelectBySpecialKey('operNumber', row.orderNum)
        //               }
        //             })
        //           }
        //         })
        //       }
        //     })
        //   })
        //   break
        case 'discount':
          break
        // case 'defaultInFlag':
        //   break
        // case 'defaultOutFlag':
        //   break
        case 'barCode':
        case 'name':
          this.form.validateFields((err, values) => {
            // 这里做逻辑处理D
            param = {
              materialId: this.materialIds,
              mpList: getMpListShort(Vue.ls.get('materialPropertyList')), //扩展属性
              prefixNo: this.prefixNo,
              depotId: row.depotId,
              organId: values.organId
            }
            getMaterialByBarCode(param).then(res => {
              if (res && res.code === 200) {
                let mList = res.data
                if (value.indexOf(',') > -1) {
                  //多个条码
                  this.$refs.materialDataTable.getValues((error, values) => {
                    values.pop() //移除最后一行数据
                    let mArr = this.materialTable.dataSource
                    for (let i = 0; i < mList.length; i++) {
                      let mInfo = mList[i]
                      this.changeColumnShow(mInfo)
                      let mObj = this.parseInfoToObj(mInfo)
                      mObj.unit = mInfo.commodityUnit || mInfo.unitName
                      mObj.depotId = mInfo.depotId
                      mObj.stock = mInfo.stock
                      mObj.materialId = mInfo.id
                      mObj.custom8 = mInfo.originalUnitPrice
                      mObj.priceNote = mInfo.priceNote
                      mArr.push(mObj)
                    }
                    let taxLastMoneyTotal = 0
                    for (let j = 0; j < mArr.length; j++) {
                      taxLastMoneyTotal += mArr[j].taxLastMoney - 0
                      //组合和拆分单据给商品类型进行重新赋值
                      if (j === 0) {
                        mArr[0].mType = this.$t('otherJS.union')
                      } else {
                        mArr[j].mType = this.$t('otherJS.primaryChild')
                      }
                      if (j === 0) {
                        mArr[0].mType = this.$t('otherJS.union')
                      } else {
                        mArr[j].mType = this.$t('otherJS.primaryChild')
                      }
                      
                    }
                    console.log(mArr, 'mArr-------------');
                    // 去重
                    let arr = [...new Set(mArr.map(v => v.id))]
                    let newArr = []
                    arr.forEach(val => {
                      let item = mArr.find(v => v.id === val)
                      newArr.push(item)
                    })
                    this.materialTable.dataSource = newArr
                    target.statisticsColumns.taxLastMoney = taxLastMoneyTotal
                    that.autoChangePrice(target)
                  })
                } else {
                  let meId = mList[0].meId
                  //单个条码
                  findStockByDepotAndBarCode({ depotId: row.depotId, meId: meId }).then(res => {
                    if (res && res.code === 200) {
                      let mArr = []
                      let mInfo = mList[0]
                      this.changeColumnShow(mInfo);
                      let mInfoEx = this.parseInfoToObj(mInfo);
                      mInfoEx.unit = mInfo.commodityUnit || mInfo.unitName
                      mInfoEx.stock = res.data.stock
                      mInfoEx.materialId = mInfo.id
                      mInfoEx.name = mInfo.name
                      mInfoEx.custom8 = mInfo.originalUnitPrice
                      let mObj = {
                        rowKey: row.id,
                        values: mInfoEx
                      }

                      mArr.push(mObj)
                      mArr.forEach(item => {
                        item.values.operNumber = ''
                      })
                      // 去重
                      let item = this.materialTable.dataSource.find(v=>v.id === mInfo.id)
                      let canMultPreFixNos = ['MMTJ']
                      if(!item || canMultPreFixNos.includes(this.prefixNo)){
                        if(canMultPreFixNos.includes(this.prefixNo)){
                          // 修改rowKey
                          mArr.forEach(v=>{
                            v.values.id = randomUUID()
                          })
                        }
                        console.log('mArr :>> ', mArr);
                        target.setValues(mArr)
                        this.materialTable.dataSource.push(mObj.values);
                        console.log(this.materialTable.dataSource,'this.materialTable.dataSource1'); 
                      }else{
                        this.$message.warning(this.$t('popup.multipleSelected'))
                      }
                      // 组装拆分
                      for (let j = 0; j < this.materialTable.dataSource.length; j++) {
                        //组合和拆分单据给商品类型进行重新赋值
                        if (j === 0) {
                          this.materialTable.dataSource[0].mType = '组合件'
                          this.materialTable.dataSource[0].mTypeShow = this.$t('otherJS.union')
                          // 拿到主商品，用于商品选择组件穿透传值
                          this.materialColor = this.materialTable.dataSource[0].color
                        } else {
                          this.materialTable.dataSource[j].mType = '普通子件'
                          this.materialTable.dataSource[j].mTypeShow = this.$t('otherJS.primaryChild')
                        }
                      }
                      target.recalcAllStatisticsColumns()
                      that.autoChangePrice(target)
                      
                      target.autoSelectBySpecialKey('operNumber', row.orderNum)
                    }
                  })
                }
              } else {
                this.$message.error(res.data)
              }
            })
            this.changeMaterialIds()
          })
          break
        case 'snList':
          console.log('snlist');
          snList = value
          if (snList) {
            snList = snList.replaceAll('，', ',')
            let snArr = snList.split(',')
            operNumber = snArr.length
            taxRate = row.taxRate - 0 //税率
            unitPrice = row.unitPrice - 0 //单价
            allPrice = (unitPrice * operNumber).toFixed(2) - 0
            taxMoney = (taxRate * 0.01 * allPrice).toFixed(2) - 0
            taxLastMoney = (allPrice + taxMoney).toFixed(2) - 0
            target.setValues([
              {
                rowKey: row.id,
                values: { operNumber: operNumber, allPrice: allPrice, taxMoney: taxMoney, taxLastMoney: taxLastMoney }
              }
            ])
            target.recalcAllStatisticsColumns()
            that.autoChangePrice(target)
          }
          break
        case 'batchNumber':
          console.log('batchNumber');
          batchNumber = value
          getBatchNumberList({ name: '', depotId: row.depotId, barCode: row.meId, batchNumber: batchNumber }).then(
            res => {
              if (res && res.code === 200) {
                if (res.data && res.data.rows) {
                  let info = res.data.rows[0]
                  operNumber = info.totalNum
                  taxRate = row.taxRate - 0 //税率
                  unitPrice = row.unitPrice - 0 //单价
                  allPrice = (unitPrice * operNumber).toFixed(2) - 0
                  taxMoney = (taxRate * 0.01 * allPrice).toFixed(2) - 0
                  taxLastMoney = (allPrice + taxMoney).toFixed(2) - 0
                  target.setValues([
                    {
                      rowKey: row.id,
                      values: {
                        expirationDate: info.expirationDateStr,
                        operNumber: operNumber,
                        allPrice: allPrice,
                        taxMoney: taxMoney,
                        taxLastMoney: taxLastMoney
                      }
                    }
                  ])
                  target.recalcAllStatisticsColumns()
                  that.autoChangePrice(target)
                }
              }
            this.clearDisabled()

            }
          )
          break
        case 'operNumber':
          this.submitBtnDisabled = true;
          let _num = Number(value)
          // let _stock = Number(row.stock)
          // if (_num > _stock) {
          //   _num = _stock
          //   target.setValues([
          //     {
          //       rowKey: row.id,
          //       values: {
          //         operNumber: _num
          //       }
          //     }
          //   ])
          // }          
          if (_num < Number(row.differNumber)) {
            target.setValues([
              {
                rowKey: row.id,
                values: {
                  differNumber: _num
                }
              }
            ])
          }
          operNumber = _num;
          taxRate = row.taxRate - 0 //税率
          unitPrice = row.unitPrice - 0 //单价
          allPrice = (unitPrice * operNumber).toFixed(2) - 0;
          taxUnitPrice = (unitPrice / ((100 + taxRate) / 100)).toFixed(2) - 0;
          taxMoney = (allPrice - taxUnitPrice * operNumber).toFixed(2) - 0
          taxLastMoney = allPrice;
          target.setValues([
            {
              rowKey: row.id,
              values: {
                allPrice: allPrice,
                taxUnitPrice: taxUnitPrice,
                taxMoney: taxMoney,
                taxLastMoney: taxLastMoney,
                operNumber:value
              }
            }
          ])
          // console.log(`row.unitPrice:${row.unitPrice}` , `operNumber:${operNumber}`,`allPrice:${allPrice}`)
          target.recalcAllStatisticsColumns()
          that.autoChangePrice(target)
          // 数量为空需要重置商品信息，因为满减会修改价格
          if (!operNumber){
            return
          }
          console.log('this.materialTable.dataSource1:', this.materialTable.dataSource)

          this.$refs.materialDataTable.getValues((error, values) => {
            console.log('values :>> ', values);
            console.log('row :>> ', row);
            console.log('value :>> ', value);
            // this.materialTable.dataSource = values
            console.log('this.materialTable.dataSource:', this.materialTable.dataSource)
            let organId = this.form.getFieldValue('organId')
            if (!organId) organId = ''
            // 赠品或者没有商品id就不走活动流程,不是采购订单，厂家直发订单，销售订单的就不走活动流程
            const prefixNoArr=['CJZF','CGDD','XSDD']
            console.log('row.materialId :>> ', row.materialId);
            if (!(prefixNoArr.includes(this.prefixNo)) || !row.materialId || (row.sourceId && (row.priceNote === '赠品' || row.priceNote === 'gift'))) {
              this.submitBtnDisabled = false;
              console.log('des :>> ', '赠品或者没有商品id就不走活动流程,不是采购订单，厂家直发订单，销售订单的就不走活动流程');
              return;
            }
            // 因为优惠活动导致价格等数据变更，所以数量变动需要重置价格及其他金额
            const getMaterialInfo = ()=>{
              return new Promise((resolve, reject) => {
                this.form.validateFields((err, values) => {
                  let mparam = {
                    materialId: row.id,
                    mpList: getMpListShort(Vue.ls.get('materialPropertyList')), //扩展属性
                    prefixNo: this.prefixNo,
                    depotId: row.depotId,
                    organId: values.organId
                  }
                  getMaterialByBarCode(mparam).then(res => {
                    let mInfo = res.data[0]
                    let index = this.materialTable.dataSource.findIndex(v=>v.id === row.id)
                    taxRate = mInfo.taxRate - 0 //税率
                    unitPrice = mInfo.billPrice - 0 //单价
                    allPrice = (unitPrice * operNumber).toFixed(2) - 0;
                    taxUnitPrice = (unitPrice / ((100 + taxRate) / 100)).toFixed(2) - 0;
                    taxMoney = (allPrice - taxUnitPrice * operNumber).toFixed(2) - 0
                    taxLastMoney = allPrice;
                    let changeInfo = {
                      taxUnitPrice: taxUnitPrice,
                      unitPrice: mInfo.billPrice,
                      allPrice: allPrice,
                      taxMoney: taxMoney,
                      taxLastMoney: taxLastMoney,
                    }
                    let rowInfo = Object.assign(row,changeInfo)
                    
                    target.setValues([
                      {
                        rowKey: row.id,
                        values: changeInfo
                      }
                    ])
                    // this.materialTable.dataSource.splice(index,1,rowInfo)
                    param = {
                      materialId: row.materialId,
                      allPrice: allPrice,
                      custom11: this.promotionOrderType,
                      organId:values.organId || ''
                    }
                    resolve(param)
                  })
                })
              })
            }
              // 马上调用活动，禁用当前行
              // this.setGiftNumberInputType(target,row)
              getMaterialInfo().then((param)=>
                getDiscount(param).then(res => {
                if (res && res.code === 200) {
                  unitPrice = (res.data.allPrice / operNumber).toFixed(2)
                  taxUnitPrice = (unitPrice / ((100 + taxRate) / 100)).toFixed(2)
                  taxMoney = (res.data.allPrice - taxUnitPrice * operNumber).toFixed(2)
                  let index = this.materialTable.dataSource.findIndex(v=>v.id === row.id)
                    let changeInfo = {
                      taxUnitPrice: taxUnitPrice,
                      taxMoney: taxMoney,
                      allPrice: res.data.allPrice,
                      taxLastMoney: res.data.allPrice,
                      unitPrice: unitPrice,
                      priceNote: res.data.priceNote || row.priceNote,
                    }
                    let rowInfo = Object.assign(row,changeInfo)
                    target.setValues([
                      {
                        rowKey: row.id,
                        values: changeInfo
                      }
                    ])
                    // this.materialTable.dataSource.splice(index,1,rowInfo)
                  target.recalcAllStatisticsColumns()
                  setTimeout(()=>{
                    that.autoChangePrice(target)
                  },500);
                }else{
                  this.$message.error(res.msg || res.data)
                }
              }).then(()=>{
                if (row.priceNote) {
                } else {
                  row.priceNote = ''
                }
                // this.materialTable.dataSource = values
                param = {
                  materialId: row.materialId,
                  operNumber: operNumber,
                  materialUnit: row.unit,
                  priceNote: row.priceNote,
                  custom11: this.promotionOrderType,//促销活动类型
                  organId:organId || '',
                  depotId:row.depotId
                }
                // 活动
                getNumber(param).then(res => {
                  let mList = res.data
                  if (res.data && res.data.length !== 0 && res.code === 200) {
                      // 清除原来的赠品
                    target.getValues(async (err,values)=>{
                      mList.forEach(async val => {
                        let index = values.findIndex(v => v.sourceId === val.sourceId)
                        if (index > -1) {
                          let item = values[index]
                          if ((item.priceNote === '赠品' || item.priceNote === 'gift') && row.materialId == val.sourceId) {
                            let ids = values.filter(v=>v.sourceId === val.sourceId).map(v=>v.id)
                            target.removeRows(ids)
                          } 
                        }
                      })
                      for (let i = 0; i < mList.length; i++) {
                        let mInfo = mList[i]
                        this.changeColumnShow(mInfo)
                        let mObj = this.parseInfoToObj1(mInfo)
                        mObj.stock = mInfo.stock
                        mObj.remark = mObj.priceNote
                        mObj.custom4 = mInfo.sourceId
                        // mObj.materialId = mInfo.id
                        // 需要删除，否则报损选项异常
                        delete mObj.materialId
                        mObj.sourceId = mInfo.sourceId
                        mObj.depotId = row.depotId || ''
                        mObj.id = randomUUID()
                        // 供应商
                        mObj.supplier = row.supplier
                        // 重新添加更新后的赠品
                        const delay = ()=>{
                          this.submitBtnDisabled = true
                            if(this.$refs[this.refKeys[0]].inputing){
                              // 延迟执行
                              setTimeout(()=>{
                                  console.log('延迟中 :>> ');
                                  delay()
                              }, 1111);
                            }else{
                              // 处理赠品Input 为disable
                              setTimeout(()=>{
                                this.$nextTick(()=>{
                                  target.push(mObj)
                                  this.submitBtnDisabled = false
                                  // 禁用赠品编辑
                                  this.$nextTick(()=>{
                                    this.setGiftNumberInputType(target,mObj)
                                  })
                                })
                              },200);
                              
                            }
                        }
                        delay()
                        
                      }
                    })
                    
                    
                  } else {
                    console.log('不是赠品 :>> ', '不是赠品');
                    // 修改数量后，没有满送则清空对应的赠品
                    if(row.priceNote !== '赠品' && row.priceNote !=='gift' && !row.sourceId && !row.custom4){
                      target.getValues((err,values)=>{
                        for (let i = values.length - 1; i>=0; i--) {
                          // 当前row不是赠品
                          if(values[i].sourceId === row.materialId){
                            // values.splice(i,1)
                            target.removeRows(values[i].id)
                          }  
                        }
                      })
                      
                    }
                  }

                }).then(()=>{
                  let param ={
                    materialId: row.materialId,
                    operNumber: operNumber,
                    custom11: this.promotionOrderType,//促销活动类型
                    organId:organId || '',
                  }
                  getSpecial(param).then(res=>{
                    if(res && res.code === 200 && res.data.flag){
                      unitPrice = res.data.specialPrice
                      taxUnitPrice = (unitPrice / ((100 + taxRate) / 100)).toFixed(2)
                      taxMoney = (unitPrice - taxUnitPrice).toFixed(2)
                      let index = this.materialTable.dataSource.findIndex(v=>v.id === row.id)
                        let changeInfo = {
                          taxUnitPrice: taxUnitPrice,
                          taxMoney: taxMoney,
                          allPrice: toDecimal(res.data.specialPrice * operNumber),
                          taxLastMoney: toDecimal(res.data.specialPrice * operNumber),
                          unitPrice: unitPrice,
                          priceNote: res.data.priceNote || row.priceNote,
                        }
                        let rowInfo = Object.assign(row,changeInfo)
                        // this.materialTable.dataSource.splice(index,1,rowInfo)
                        
                      target.setValues([
                        {
                          rowKey: row.id,
                          values: changeInfo
                        }
                      ])
                      target.recalcAllStatisticsColumns()
                      setTimeout(()=>{
                        that.autoChangePrice(target)
                      },500);
                    }else if(res.code !== 200){
                      this.$message.warning(res.msg)
                    }
                    this.submitBtnDisabled = false
                    // 活动调用结束释放当前行
                    // this.setGiftNumberInputType(target,row,false)
                  })
                })
                

              }))
          })
          
          break
        case 'unitPrice':
          operNumber = row.operNumber - 0 //数量
          unitPrice = value - 0 //单价
          taxRate = row.taxRate - 0 //税率
          allPrice = (unitPrice * operNumber).toFixed(2) - 0
          taxUnitPrice = (unitPrice / ((100 + taxRate) / 100)).toFixed(2) - 0
          taxMoney = (allPrice - taxUnitPrice * operNumber).toFixed(2) - 0
          taxLastMoney = allPrice
          target.setValues([
            {
              rowKey: row.id,
              values: { allPrice: allPrice, taxUnitPrice: taxUnitPrice, taxMoney: taxMoney, taxLastMoney: taxLastMoney }
            }
          ])
          target.recalcAllStatisticsColumns()
          that.autoChangePrice(target)
          break
        case 'allPrice':
          operNumber = row.operNumber - 0 //数量
          taxRate = row.taxRate - 0 //税率
          allPrice = value - 0
          unitPrice = (allPrice / operNumber).toFixed(2) - 0 //单价
          taxUnitPrice = (unitPrice / ((100 + taxRate) / 100)).toFixed(2) - 0
          taxMoney = (allPrice - taxUnitPrice * operNumber).toFixed(2) - 0
          taxLastMoney = allPrice
          target.setValues([
            {
              rowKey: row.id,
              values: {
                unitPrice: unitPrice,
                taxUnitPrice: taxUnitPrice,
                taxMoney: taxMoney,
                taxLastMoney: taxLastMoney
              }
            }
          ])
          param = {
            materialId: this.materialIds,
            allPrice: allPrice
          }
          getDiscount(param).then(res => {
            console.log('3')
            if (res && res.code === 200) {
              unitPrice = (res.data.allPrice / operNumber).toFixed(2)
              ;(taxUnitPrice = (unitPrice / ((100 + taxRate) / 100)).toFixed(2)),
                (taxMoney = (res.data.allPrice - taxUnitPrice * operNumber).toFixed(2)),
                target.setValues([
                  {
                    rowKey: row.id,
                    values: {
                      taxUnitPrice: taxUnitPrice,
                      taxMoney: taxMoney,
                      allPrice: res.data.allPrice,
                      taxLastMoney: res.data.allPrice,
                      unitPrice: unitPrice,
                      priceNote: res.data.priceNote
                    }
                  }
                ])
              target.recalcAllStatisticsColumns()
              that.autoChangePrice(target)
            }
          })
          // target.recalcAllStatisticsColumns()
          // that.autoChangePrice(target)
          break
        case 'taxRate':
          operNumber = row.operNumber - 0 //数量
          allPrice = row.allPrice - 0
          unitPrice = row.unitPrice - 0
          taxRate = value - 0 //税率
          taxUnitPrice = (unitPrice / ((100 + taxRate) / 100)).toFixed(2) - 0
          taxMoney = (allPrice - taxUnitPrice * operNumber).toFixed(2) - 0
          taxLastMoney = allPrice
          target.setValues([
            { rowKey: row.id, values: { taxUnitPrice: taxUnitPrice, taxMoney: taxMoney, taxLastMoney: taxLastMoney } }
          ])
          target.recalcAllStatisticsColumns()
          that.autoChangePrice(target)
          
          break
        case 'taxLastMoney':
          operNumber = row.operNumber - 0 //数量
          taxLastMoney = value - 0
          taxRate = row.taxRate - 0 //税率
          unitPrice = (taxLastMoney / operNumber).toFixed(2) - 0
          allPrice = (unitPrice * operNumber).toFixed(2) - 0
          taxUnitPrice = (unitPrice / ((100 + taxRate) / 100)).toFixed(2) - 0
          taxMoney = (allPrice - taxUnitPrice * operNumber).toFixed(2) - 0
          target.setValues([
            {
              rowKey: row.id,
              values: { taxUnitPrice: taxUnitPrice, unitPrice: unitPrice, allPrice: allPrice, taxMoney: taxMoney }
            }
          ])
          target.recalcAllStatisticsColumns()
          that.autoChangePrice(target)
          break
      }
      if(column.key!=='operNumber'){//operNumber触发太多活动了不能提前触发此状态
        this.submitBtnDisabled = false
      }
    },
    onBlurChange(event){
      // this.disabledRowIds = [];
      // this.$refs.materialDataTable.disabledRowIds = []
      // this.materialTable.dataSource.push({})
      // this.materialTable.dataSource.pop()
      // console.log(this.$refs.materialDataTable.disabledRowIds,'lll');
    },
    // 清空禁用的行
    clearDisabled(){
      this.disabledRowIds = [];
      this.$refs.materialDataTable.disabledRowIds = []
      this.materialTable.dataSource.push({})
      this.materialTable.dataSource.pop()
    },

    getMaterialInfo(depotId){
      return new Promise((resolve, reject) => {
        let param = {
          materialId: this.materialIds,
          mpList: getMpListShort(Vue.ls.get('materialPropertyList')), //扩展属性
          // 为何 this.depotId || row.depotId ？ 因为盘点单新增的时候，表头选择了仓库，表体加载完option后又默认选第一个了
          depotId: depotId
        }
        getMaterialByBarCode(param).then(res => {
          resolve(res)
        })
      })
    },
    // 采购管理-条码barCode修改事件触发
    barCodeValueChange (event) {
      let that = this
      const { type, row, column, value, target } = event
      let param, snList, batchNumber, operNumber, unitPrice, allPrice, taxRate, taxMoney, taxLastMoney
      this.materialIds = localStorage.getItem('materialIds')
      console.log('column.key:'+column.key)
      switch (column.key) {
        case 'barCode':
        case 'name':
          this.$set(this.materialTable,'loading',true)
          // return;
          this.form.validateFields((err, values) => {
            // 这里做逻辑处理
            param = {
              materialId: this.materialIds,
              mpList: getMpListShort(Vue.ls.get('materialPropertyList')), //扩展属性
              prefixNo: this.prefixNo,
              organId: values.organId,
              // 为何 this.depotId || row.depotId ？ 因为盘点单新增的时候，表头选择了仓库，表体加载完option后又默认选第一个了
              depotId: this.depotId || row.depotId || ''
            }
            getMaterialByBarCode(param).then(res => {
              if (res && res.code === 200) {
                let mList = res.data
                if (true) {
                  // value.indexOf(',') > -1
                  //多个条码
                  this.$refs.materialDataTable.getValues((error, values) => {
                    // values.pop() //移除最后一行数据
                    // 删除空数据
                    for(let i= values.length-1;i>=0;i--){
                      if(!values[i].materialId){
                        values.splice(i,1)
                      }
                    }
                    let mArr = values//this.materialTable.dataSource
                    console.log('mArr :>> ', mArr);
                    for (let i = 0; i < mList.length; i++) {
                      let mInfo = mList[i]
                      this.changeColumnShow(mInfo)
                      let mObj = this.parseInfoToObj(mInfo)
                      mObj.depotId = mInfo.depotId
                      mObj.stock = mInfo.stock
                      mObj.materialId = mInfo.id
                      mObj.priceNote = mInfo.priceNote
                      mObj.name = mInfo.name
                      mObj.unit = mInfo.commodityUnit || mInfo.unitName
                      mObj.custom11 = '0'
                      mObj.differNumber = 0
                      mObj.organName = mObj.supplier//设置供应商
                      mObj.custom8 = mInfo.originalUnitPrice
                      mObj.remark = mInfo.priceNote
                      mObj.categoryName = mInfo.categoryName
                      let item = mArr.find(v=>v.id === mObj.id)
                      if(!item){
                        mArr.push(mObj)
                      }
                    }
                    let taxLastMoneyTotal = 0
                    for (let j = 0; j < mArr.length; j++) {
                      taxLastMoneyTotal += mArr[j].taxLastMoney - 0
                      //组合和拆分单据给商品类型进行重新赋值
                      if (j === 0) {
                        mArr[0].mType = '组合件'
                        mArr[0].mTypeShow = this.$t('otherJS.union')
                      } else {
                        mArr[j].mType = '普通子件'
                        mArr[j].mTypeShow = this.$t('otherJS.primaryChild')
                      }
                      if (values[j]) {
                        mArr[j].custom11 = values[j].custom11
                        mArr[j].differNumber = values[j].differNumber
                        mArr[j].operNumber = values[j].operNumber
                      } 
                    }
                    let arr = [...new Set(mArr.map(v => v.id))]
                    let newArr = []
                    arr.forEach(val => {
                      let item = mArr.find(v => v.id === val)
                      let defaultItem = values.find(v=>v.id === val)
                      if(item && defaultItem){
                        item = Object.assign(item,defaultItem)
                      }
                      newArr.push(item)
                    })
                    console.log('newArr :>> ', newArr);
                    // target.pushArray(newArr)
                    this.materialTable.dataSource = newArr
                    target.statisticsColumns.taxLastMoney = taxLastMoneyTotal
                    // 聚焦新增的行
                    this.$nextTick(()=>{

                      setTimeout(()=>{
                        const input = document.querySelectorAll(`#operNumber${target.caseId + mList[0].id}`)
                        input && input.length && input[0].focus()
                      },200);
                      
                    })
                    that.autoChangePrice(target)
                  })
                } else {
                  //单个条码
                  let meId = mList[0].meId
                  findStockByDepotAndBarCode({ depotId: this.depotId || row.depotId, meId: meId }).then(res => {
                    if (res && res.code === 200) {
                      let mArr = []
                      let mInfo = mList[0]
                      this.changeColumnShow(mInfo)
                      let mInfoEx = this.parseInfoToObj(mInfo)
                      mInfoEx.stock = res.data.stock
                      mInfoEx.materialId = mInfo.id
                      mInfoEx.unit = mInfo.commodityUnit || mInfo.unitName
                      mInfoEx.operNumber = ''
                      mInfoEx.organName = mInfoEx.supplier
                      mInfoEx.custom8 = mInfo.originalUnitPrice
                      mInfoEx.remark = mInfo.priceNote
                      let mObj = {
                        rowKey: row.id,
                        values: mInfoEx
                      }
                      mArr.push(mObj)
                      console.log(mInfoEx, 'mInfoEx');
                      // target.setValues(mArr)
                      target.recalcAllStatisticsColumns()
                      that.autoChangePrice(target)
                      let arr  = mArr.map(item => item.values);
                      // this.materialTable.dataSource = arr

                      this.$refs.materialDataTable.getValues((error, values) => {
                        console.log('values111 :>> ', values);
                        if(!values[0].materialId){
                          this.materialTable.dataSource = []
                        }
                      // 单选时不替换，非重复则增加

                        // arr.forEach(val=>{
                        //   let boolean = this.materialTable.dataSource.some(v=>v.id === val.id)
                        //   if(!boolean){
                        //     // this.materialTable.dataSource.push(val)
                        //     target.push(val)
                        //   }else{
                        //     this.$message.warning(this.$t('popup.multipleSelected'))
                        //   }
                        // })
                        
                        let boolean = this.materialTable.dataSource.some(v=>v.id === row.id)
                        if(!boolean){
                          values.push(mInfoEx)
                          values = values.filter(v=>v.materialId)
                          this.materialTable.dataSource.splice(0,this.materialTable.dataSource.length,...values)
                        }else{
                          this.$message.warning(this.$t('popup.multipleSelected'))
                        }
                        // this.materialTable.dataSource.forEach((item, index) => {
                        //   item.custom11 = values[index] && values[index].custom11
                        //   item.differNumber = values[index] && values[index].differNumber || 0
                        //   if (index === 0) {
                        //     item.mType = '组合件'
                        //     item.mTypeShow = this.$t('otherJS.union')
                        //   } else {
                        //     item.mType = '普通子件'
                        //     item.mTypeShow = this.$t('otherJS.primaryChild')
                        //   }
                        // })
                        
                        if (this.shopMaterialId == '' && values[0].materialId) {
                          this.shopMaterialId = values[0].materialId
                          this.shopBarCode = values[0].barCode
                        }
                        values.forEach(item => {
                          item.giftMaterialId = item.materialId // 赠品自己
                          item.materialId = this.shopMaterialId // 上面商品ID
                          // item.operNumber = ''
                          // if (mInfoEx.barCode == item.barCode) {
                          //   mInfoEx.giftMaterialId = item.materialId
                          //   mInfoEx.materialId = this.shopMaterialId
                          //   target.setValues(mArr)
                          // }
                          this.shopIdList.push(item)
                        })
                        let arr1 = this.fn2(this.shopIdList)
                        this.shopIdList = arr1
                        console.log(this.shopIdList)
                        // localStorage.setItem('shopIdList', JSON.stringify(this.shopIdList))
                      })
                      // this.materialTable1.dataSource = mInfoEx
                      target.autoSelectBySpecialKey('operNumber', row.orderNum)
                    }
                  })
                }
              } else {
                this.$message.error(res.data)
              }
              setTimeout(() => {
                this.$set(this.materialTable,'loading',false)
                this.submitBtnDisabled = false
              }, 300);
            })
            this.changeMaterialIds()
          })
          break
      }
    },
    // 商品管理
    onValueChange1 (event) {
      console.log(event,666);
      console.log(this.giftCurrentIndex,6666);
      let that = this
      console.log(that.materialTable.dataSource,'that.materialTable.dataSource');
      if (that.materialTable.dataSource.length == 0) {
        that.$message.error('商品未选择，不能选择赠品')
        that.materialTable1.dataSource = []
        return
      }
      // let materialIds = ''
      const { type, row, column, value, target } = event
      let param, snList, batchNumber, operNumber, unitPrice, allPrice, taxRate, taxMoney, taxLastMoney
      // console.log(type, row, column, value, target)
      this.materialIds = localStorage.getItem('materialIds')
      // row.materialId = row.id
      console.log(row)
      // console.log(column.key)
      switch (column.key) {
        case 'depotId':
          // if (row.barCode) {
          //   that.getStockByDepotBarCode(row, target)
          // }
          break
        case 'allPrice':
          break
        // case 'unit':
        //   break
        case 'discount':
          // row.discount =
          // console.log(row)
          break
        // case 'defaultInFlag':
        //   break
        // case 'defaultOutFlag':
        //   break
        case 'barCode':
        case 'name':
          this.form.validateFields((err, values) => {
            // 这里做逻辑处理
            param = {
              materialId: this.materialIds,
              mpList: getMpListShort(Vue.ls.get('materialPropertyList')), //扩展属性
              prefixNo: this.prefixNo,
              organId: values.organId,
              depotId: row.depotId
            }
            getMaterialByBarCode(param).then(res => {
              if (res && res.code === 200) {
                let mList = res.data
                if (value.indexOf(',') > -1) {
                  //多个条码
                  this.$refs.materialDataTable.getValues((error, values) => {
                    values.pop() //移除最后一行数据
                    let mArr = this.materialTable1.dataSource

                    for (let i = 0; i < mList.length; i++) {
                      let mInfo = mList[i]
                      this.changeColumnShow(mInfo)
                      let mObj = this.parseInfoToObj(mInfo)
                      mObj.depotId = mInfo.depotId
                      mObj.stock = mInfo.stock
                      console.log(this.giftCurrentIndex,'this.giftCurrentIndex');
                      mObj.materialId = this.materialTable.dataSource[this.giftCurrentIndex].materialId //主商品Id
                      mObj.giftMaterialId = mInfo.giftMaterialId//设置赠品商品id
                      mObj.giftMaterialUnit = mInfo.unit//设置赠品商品id
                      mObj.priceNote = mInfo.priceNote
                      
                      mArr.push(mObj)
                    }
                    let taxLastMoneyTotal = 0
                    for (let j = 0; j < mArr.length; j++) {
                      taxLastMoneyTotal += mArr[j].taxLastMoney - 0
                      //组合和拆分单据给商品类型进行重新赋值
                      if (j === 0) {
                        mArr[0].mType = '组合件'
                        mArr[0].mTypeShow = this.$t('otherJS.union')
                      } else {
                        mArr[j].mType = '普通子件'
                        mArr[j].mTypeShow = this.$t('otherJS.primaryChild')
                      }
                    }
                    // 去重
                    let arr = [...new Set(mArr.map(v => v.id))]
                    let newArr = []
                    arr.forEach(val => {
                      let item = mArr.find(v => v.id === val)
                      newArr.push(item)
                    })
                    this.materialTable1.dataSource = newArr
                    target.statisticsColumns.taxLastMoney = taxLastMoneyTotal
                    that.autoChangePrice(target)
                    if (this.shopMaterialId == '') {
                      this.shopMaterialId = this.materialTable.dataSource[0].materialId
                      this.shopBarCode = this.materialTable.dataSource[0].barCode
                    }
                    this.materialTable1.dataSource.forEach(item => {
                      item.giftMaterialId = item.id
                      item.materialId = this.shopMaterialId
                      this.shopIdList.push(item)
                    })
                    let arr1 = this.fn3(this.shopIdList)
                    this.shopIdList = arr1
                    // 存到主商品上去
                    
                    this.materialTable.dataSource[this.giftCurrentIndex].shopIdList = this.materialTable1.dataSource
                    console.log(this.materialTable.dataSource,6666);
                    // localStorage.setItem('shopIdList', JSON.stringify(this.shopIdList))
                  })
                } else {
                  //单个条码
                  console.log(this.materialTable.dataSource,'this.materialTable.dataSource');
                  let meId = mList[0].meId
                  findStockByDepotAndBarCode({ depotId: row.depotId, meId: meId }).then(res => {
                    if (res && res.code === 200) {
                      let mArr = []
                      let mInfo = mList[0]
                      this.changeColumnShow(mInfo)
                      let mInfoEx = this.parseInfoToObj(mInfo)
                      mInfoEx.stock = res.data.stock
                      mInfoEx.materialId = this.materialTable.dataSource[this.giftCurrentIndex].materialId //主商品Id
                      mInfoEx.giftMaterialId = mInfo.id//设置赠品商品id
                      mInfoEx.giftMaterialUnit = mInfo.unit//设置赠品商品单位

                      let mObj = {
                        rowKey: row.id,
                        values: mInfoEx
                      }
                      mArr.push(mObj)
                      // 去重
                      let item = this.materialTable1.dataSource.find(v=>v.id === mInfo.id)
                      let canMultPreFixNos = ['MMTJ']
                      if(!item || canMultPreFixNos.includes(this.prefixNo)){
                        this.materialTable1.dataSource = this.materialTable1.dataSource.filter(v=>v.id)
                        this.materialTable1.dataSource.push(mObj.values);
                      }else{
                        this.$message.warning(this.$t('popup.multipleSelected'))
                      }
                      // this.materialTable1.dataSource.push()
                      target.recalcAllStatisticsColumns()
                      that.autoChangePrice(target)
                      this.materialTable.dataSource[this.giftCurrentIndex].shopIdList = this.materialTable1.dataSource

                      // 历史逻辑
                      // this.$refs.materialDataTable1.getValues((error, values) => {
                      //   console.log(values,'77777------');
                      //   if (this.shopMaterialId == '') {
                      //     this.shopMaterialId = this.materialTable.dataSource[0].materialId
                      //     this.shopBarCode = this.materialTable.dataSource[0].barCode
                      //   }
                      //   this.materialTable1.dataSource.forEach(item => {
                      //     item.giftMaterialId = item.materialId // 赠品自己
                      //     item.materialId = this.shopMaterialId // 上面商品ID
                      //     // if (mInfoEx.barCode == item.barCode) {
                      //     //   mInfoEx.giftMaterialId = item.materialId
                      //     //   mInfoEx.materialId = this.shopMaterialId
                      //     //   target.setValues(mArr)
                      //     // }
                      //     this.shopIdList.push(item)
                      //   })
                      //   let arr1 = this.fn2(this.shopIdList)
                      //   this.shopIdList = arr1
                      //   console.log(arr1,'99999999----------');

                        // 将赠品绑定到主商品
                        // localStorage.setItem('shopIdList', JSON.stringify(this.shopIdList))
                      // })
                      // this.materialTable1.dataSource = mInfoEx

                      target.autoSelectBySpecialKey('operNumber', row.orderNum)
                    }
                  })
                }
              } else {
                this.$message.error(res.data)
              }
            })
            this.changeMaterialIds()
          })
          break
        case 'giftQuantity':
          this.shopIdList.forEach(item => {
            if (item.materialId == row.materialId && item.name == row.name) {
              item.giftQuantity = row.giftQuantity
            }
          })
          this.materialTable.dataSource[this.giftCurrentIndex].shopIdList.forEach(item => {
            if (item.materialId == row.materialId && item.name == row.name) {
              item.giftQuantity = row.giftQuantity
            }
          })
          break
      }
    },
    //转为商品对象
    parseInfoToObj(mInfo) {
      const obj = {
        barCode: mInfo.mBarCode,
        name: mInfo.name,
        standard: mInfo.standard,
        model: mInfo.model,
        priceNote: mInfo.priceNote,
        meId: mInfo.meId,
        color: mInfo.color,
        materialOther: mInfo.materialOther,
        unit: mInfo.commodityUnit,
        sku: mInfo.sku,
        taxUnitPrice: (mInfo.billPrice / ((100 + mInfo.taxRate) / 100)).toFixed(2),
        unitPrice: mInfo.billPrice,
        allPrice: mInfo.billPrice,
        taxRate: mInfo.taxRate,
        taxMoney: (mInfo.billPrice - (mInfo.billPrice / ((100 + mInfo.taxRate) / 100)).toFixed(2) * 1).toFixed(2),
        taxLastMoney: mInfo.billPrice
      }
      for (const key in mInfo) {
        if (Object.hasOwnProperty.call(mInfo, key) && mInfo[key] === null) {
          delete mInfo[key]
        }
      }
      return Object.assign({}, obj, mInfo,{cstom8: mInfo.taxUnitPrice})
    },
    //转为赠送商品对象
    parseInfoToObj1 (mInfo) {
      return {
        barCode: mInfo.mBarCode,
        name: mInfo.name,
        standard: mInfo.standard,
        model: mInfo.model,
        color: mInfo.color,
        priceNote: mInfo.priceNote,
        meId: mInfo.meId,
        materialOther: mInfo.materialOther,
        unit: mInfo.commodityUnit,
        sku: mInfo.sku,
        operNumber: mInfo.operNumber,
        unitPrice: mInfo.billPrice,
        allPrice: mInfo.billPrice,
        taxRate: 0,
        taxMoney: 0,
        taxLastMoney: mInfo.billPrice,
        custom8: mInfo.taxUnitPrice,
      }
    },
    //使得型号、颜色、扩展信息、sku等为隐藏
    changeColumnHide () {
      this.changeFormTypes(this.materialTable.columns, 'model', 0)
      // this.changeFormTypes(this.materialTable.columns, 'color', 0)
      this.changeFormTypes(this.materialTable.columns, 'materialOther', 1)
      this.changeFormTypes(this.materialTable.columns, 'sku', 0)
    },
    //（组装单，拆卸单使用这个方法）使得型号、颜色、扩展信息、sku等为隐藏
    changeColumnHide1 () {
      this.changeFormTypes(this.materialTable.columns, 'model', 0)
      // this.changeFormTypes(this.materialTable.columns, 'color', 0)
      this.changeFormTypes(this.materialTable.columns, 'materialOther', 0)
      this.changeFormTypes(this.materialTable.columns, 'sku', 0)
    },
    //使得sku、序列号、批号、到期日等为显示
    changeColumnShow (info) {
      if (info.model) {
        this.changeFormTypes(this.materialTable.columns, 'model', 1)
      }
      if (info.color) {
        this.changeFormTypes(this.materialTable.columns, 'color', 1)
      }
      if (info.materialOther) {
        this.changeFormTypes(this.materialTable.columns, 'materialOther', 1)
      }
      if (info.sku) {
        this.changeFormTypes(this.materialTable.columns, 'sku', 1)
      }
      if (info.enableSerialNumber === '1') {
        this.changeFormTypes(this.materialTable.columns, 'snList', 1)
      }
      // if (info.enableBatchNumber === '1') {
      //   this.changeFormTypes(this.materialTable.columns, 'batchNumber', 1)
      //   this.changeFormTypes(this.materialTable.columns, 'expirationDate', 1)
      // }
    },
    //删除一行或多行的时候触发
    onDeleted (ids, target) {
      target.recalcAllStatisticsColumns()
      this.autoChangePrice(target)
      // 更新datasource
      // ids.forEach(val=>{
      //   let index = this.materialTable.dataSource.findIndex(v=>v.id === val)
      //   if(index!== -1){
      //     this.materialTable.dataSource.splice(index,1)
      //   }
      // })
    },
    clearData() {
      // 清除商品
      if(typeof(this.materialTable.dataSource)!="undefined"){
        this.materialTable.dataSource.splice(0, this.materialTable.dataSource.length)
      }
      // 重置商品货号
      this.materialColor  = ''
      // 清空禁用的行
      this.disabledRowIds = []
      // 清除文件缓存
      localStorage.removeItem('fileListId')
      localStorage.removeItem('fileList')
    },
    //根据仓库和条码查询库存
    getStockByDepotBarCode (row, target) {
      findStockByDepotAndBarCode({ depotId: row.depotId, meId: row.meId }).then(res => {
        if (res && res.code === 200) {
          const index = this.materialTable.dataSource.findIndex(v=>v.id === row.id)
          if(index > -1){
            row.stock = res.data.stock
            this.materialTable.dataSource.splice(index,1,row)
          }
          target.recalcAllStatisticsColumns()
        }
      })
    },
    //改变优惠、本次付款、欠款的值
    autoChangePrice (target) {
      let {values} = target.getValuesAsync((e,v)=>v.values)
      // 不能使用target.statisticsColumns统计的方式计算了，价格权限会导致获取不到值
      // 也不能用dataSource,因为target.set不会触发dataSource更新
      let allTaxLastMoney = values.reduce((pre,item,index)=>{
        return pre + +item.taxLastMoney
      },0) || 0
      // let discount = this.form.getFieldValue('discount') - 0
      let otherMoney = this.form.getFieldValue('otherMoney') ? this.form.getFieldValue('otherMoney') - 0 : 0
      let deposit = this.form.getFieldValue('deposit')
      // 之前的优惠率
      // let discountMoney = (discount * 0.01 * allTaxLastMoney).toFixed(2) - 0
      console.log('allTaxLastMoney :>> ', allTaxLastMoney);
      let discountMoney = (0 * allTaxLastMoney)
      console.log('discountMoney',discountMoney);
      let discountLastMoney = this.$toDecimal(allTaxLastMoney - discountMoney)
      console.log('discountLastMoney',discountLastMoney);

      let changeAmountNew = (discountLastMoney + otherMoney).toFixed(2) - 0
      if (deposit) {
        changeAmountNew = (changeAmountNew - deposit).toFixed(2) - 0
      }
      this.$nextTick(() => {
        changeAmountNew = this.prefixNo === 'CGDD' || this.prefixNo === 'XSDD' || this.prefixNo === 'CGRK' ? 0 : changeAmountNew
        this.form.setFieldsValue({
          discountMoney: discountMoney,
          discountLastMoney: discountLastMoney,
          debt: 0,
          changeAmount: 0
        })
      })
    },
    //改变优惠率
    onKeyUpDiscount (e) {
      console.log('BUG2')
      const value = e.target.value - 0
      let otherMoney = this.form.getFieldValue('otherMoney') ? this.form.getFieldValue('otherMoney') - 0 : 0
      let deposit = this.form.getFieldValue('deposit')
      let allTaxLastMoney = this.$refs.materialDataTable.statisticsColumns.taxLastMoney - 0
      let discountMoneyNew = (allTaxLastMoney * value * 0.01).toFixed(2) - 0
      let discountLastMoneyNew = (allTaxLastMoney - discountMoneyNew).toFixed(2) - 0
      let changeAmountNew = (discountLastMoneyNew + otherMoney).toFixed(2) - 0
      if (deposit) {
        changeAmountNew = (changeAmountNew - deposit).toFixed(2) - 0
      }
      this.$nextTick(() => {
        changeAmountNew = this.prefixNo === 'CGDD' || this.prefixNo === 'XSDD' ? 0 : changeAmountNew
        this.form.setFieldsValue({
          discountMoney: discountMoneyNew,
          discountLastMoney: discountLastMoneyNew,
          changeAmount: changeAmountNew,
          debt: 0
        })
      })
    },
    //改变付款优惠
    onKeyUpDiscountMoney (e) {
      console.log('BUG3')
      const value = e.target.value - 0
      console.log('value :>> ', value);
      let otherMoney = this.form.getFieldValue('otherMoney') ? this.form.getFieldValue('otherMoney') - 0 : 0
      let deposit = this.form.getFieldValue('deposit')
      console.log('this.$refs.materialDataTable.statisticsColumns :>> ', this.$refs.materialDataTable.statisticsColumns);
      let allTaxLastMoney = this.$refs.materialDataTable.statisticsColumns.allPrice - 0
      let discountNew = ((value / allTaxLastMoney) * 100).toFixed(2) - 0
      let discountLastMoneyNew = (allTaxLastMoney - value).toFixed(2) - 0
      let changeAmountNew = (discountLastMoneyNew + otherMoney).toFixed(2) - 0
      if (deposit) {
        changeAmountNew = (changeAmountNew - deposit).toFixed(2) - 0
      }
      this.$nextTick(() => {
        changeAmountNew = this.prefixNo === 'CGDD' || this.prefixNo === 'XSDD' ? 0 : changeAmountNew
        this.form.setFieldsValue({
          discount: discountNew,
          discountLastMoney: discountLastMoneyNew,
          changeAmount: changeAmountNew,
          debt: 0
        })
      })
    },
    //其它费用
    onKeyUpOtherMoney (e) {
      console.log('BUG4')
      const value = e.target.value - 0
      let discountLastMoney = this.form.getFieldValue('discountLastMoney') - 0
      let deposit = this.form.getFieldValue('deposit')
      let changeAmountNew = (discountLastMoney + value).toFixed(2) - 0
      let otherMoney = changeAmountNew - discountLastMoney
      let backAmount = changeAmountNew - discountLastMoney - otherMoney
      let debt = 0
      if (deposit) {
        changeAmountNew = (changeAmountNew - deposit).toFixed(2) - 0
      }
      if (backAmount == 0) {
        // debt = 0
      } else if (backAmount > 0) {
        // debt = 0
      } else if (backAmount < 0) {
        debt = Math.abs(backAmount)
        backAmount = 0
      }
      this.$nextTick(() => {
        this.form.setFieldsValue({ changeAmount: changeAmountNew, debt: debt, backAmount: backAmount })
      })
    },
    //改变扣除订金
    onKeyUpDeposit (e) {
      console.log('BUG5')
      const value = e.target.value - 0
      let discountLastMoney = this.form.getFieldValue('discountLastMoney') - 0
      let otherMoney = this.form.getFieldValue('otherMoney') ? this.form.getFieldValue('otherMoney') - 0 : 0
      let changeAmountNew = (discountLastMoney + otherMoney).toFixed(2) - 0
      if (value) {
        changeAmountNew = (changeAmountNew - value).toFixed(2) - 0
      }
      this.$nextTick(() => {
        this.form.setFieldsValue({ changeAmount: changeAmountNew, debt: 0 })
      })
    },
    //改变本次付款
    onKeyUpChangeAmount (e) {
      console.log('BUG6')
      const value = e.target.value - 0
      let discountLastMoney = this.form.getFieldValue('discountLastMoney') - 0
      let otherMoney = this.form.getFieldValue('otherMoney') ? this.form.getFieldValue('otherMoney') - 0 : 0
      let deposit = this.form.getFieldValue('deposit')
      let debtNew = (discountLastMoney + otherMoney - value).toFixed(2) - 0
      let backAmount = (discountLastMoney + otherMoney - value).toFixed(2) - 0
      if (deposit) {
        debtNew = (debtNew - deposit).toFixed(2) - 0
      }
      if (debtNew <= 0) {
        // backAmount = debtNew
        debtNew = 0
      } else if (debtNew > 0) {
        backAmount = 0
      }
      this.$nextTick(() => {
        this.form.setFieldsValue({ debt: debtNew, backAmount: backAmount })
      })
    },
    scanEnter () {
      this.scanStatus = false
      this.$nextTick(() => {
        this.$refs.scanBarCode.focus()
      })
    },
    //扫码之后回车
    scanPressEnter () {
      if (this.scanBarCode) {
        this.getAllTable()
          .then(tables => {
            return getListData(this.form, tables)
          })
          .then(allValues => {
            let param = {
              barCode: this.scanBarCode,
              mpList: getMpListShort(Vue.ls.get('materialPropertyList')), //扩展属性
              prefixNo: this.prefixNo
            }
            getMaterialByBarCode(param).then(res => {
              if (res && res.code === 200) {
                let hasFinished = false
                let allLastMoney = 0
                let allTaxLastMoney = 0
                //获取单据明细列表信息
                let detailArr = allValues.tablesValue[0].values
                //构造新的列表数组，用于存放单据明细信息
                let newDetailArr = []
                for (let detail of detailArr) {
                  if (detail.barCode) {
                    //如果条码重复，就在给原来的数量加1
                    if (detail.barCode === this.scanBarCode) {
                      detail.operNumber = detail.operNumber - 0 + 1
                      //由于改变了商品数量，需要同时更新相关金额和价税合计
                      let taxRate = detail.taxRate - 0 //税率
                      let unitPrice = detail.unitPrice - 0 //单价
                      detail.allPrice = (unitPrice * detail.operNumber).toFixed(2) - 0
                      detail.taxMoney = (taxRate * 0.01 * detail.allPrice).toFixed(2) - 0
                      detail.taxLastMoney = (detail.allPrice + detail.taxMoney).toFixed(2) - 0
                      hasFinished = true
                    }
                    newDetailArr.push(detail)
                  }
                }
                if (!hasFinished) {
                  //将扫码的条码对应的商品加入列表
                  let item = {}
                  item.barCode = this.scanBarCode
                  let mList = res.data
                  if (mList && mList.length > 0) {
                    let mInfo = mList[0]
                    this.changeColumnShow(mInfo)
                    item.depotId = mInfo.depotId
                    item.name = mInfo.name
                    item.standard = mInfo.standard
                    item.model = mInfo.model
                    item.color = mInfo.color
                    item.materialOther = mInfo.materialOther
                    item.stock = mInfo.stock
                    item.unit = mInfo.commodityUnit
                    item.sku = mInfo.sku
                    item.operNumber = 1
                    item.unitPrice = mInfo.billPrice
                    item.allPrice = mInfo.billPrice
                    item.taxRate = 0
                    item.taxMoney = 0
                    item.taxLastMoney = mInfo.billPrice
                    newDetailArr.push(item)
                  } else {
                    this.$message.warning(this.$t('popup.sorryThereBarcode'))
                  }
                }
                //组合和拆分单据给商品类型进行重新赋值
                for (let i = 0; i < newDetailArr.length; i++) {
                  if (i === 0) {
                    newDetailArr[0].mType = '组合件'
                    newDetailArr[0].mType = this.$t('otherJS.union')
                  } else {
                    newDetailArr[i].mTypeShow = '普通子件'
                    newDetailArr[i].mTypeShow = this.$t('otherJS.primaryChild')
                  }
                }
                this.materialTable1.dataSource = newDetailArr
                //更新优惠后金额、本次付款等信息
                for (let newDetail of newDetailArr) {
                  allLastMoney = allLastMoney + (newDetail.allPrice - 0)
                  allTaxLastMoney = allTaxLastMoney + (newDetail.taxLastMoney - 0)
                }
                let discount = this.form.getFieldValue('discount') - 0
                let otherMoney = this.form.getFieldValue('otherMoney') ? this.form.getFieldValue('otherMoney') - 0 : 0
                let deposit = this.form.getFieldValue('deposit')
                let discountMoney = (discount * 0.01 * allTaxLastMoney).toFixed(2) - 0
                let discountLastMoney = (allTaxLastMoney - discountMoney).toFixed(2) - 0
                let changeAmountNew = (discountLastMoney + otherMoney).toFixed(2) - 0
                if (deposit) {
                  changeAmountNew = (changeAmountNew - deposit).toFixed(2) - 0
                }
                if (this.prefixNo === 'LSCK' || this.prefixNo === 'LSTH') {
                  this.$nextTick(() => {
                    this.form.setFieldsValue({ changeAmount: allLastMoney, getAmount: allLastMoney, backAmount: 0 })
                  })
                } else {
                  this.$nextTick(() => {
                    changeAmountNew = this.prefixNo === 'CGDD' || this.prefixNo === 'XSDD' ? 0 : changeAmountNew
                    this.form.setFieldsValue({
                      discount: discount,
                      discountMoney: discountMoney,
                      discountLastMoney: discountLastMoney,
                      changeAmount: changeAmountNew,
                      debt: 0
                    })
                  })
                }
                //置空扫码的内容
                this.scanBarCode = ''
                this.$refs.scanBarCode.focus()
              } else {
                this.$message.error(res.data)
              }
            })
          })
      }
    },
    stopScan () {
      this.scanStatus = true
      this.scanBarCode = ''
    },
    //保存并审核
    handleOkAndCheck () {
      this.billStatus = '1'
      this.handleOk()
    }
  }
}
